(function() {
  var express, fs, get_level, readline, readlines, router, stat_file_size;

  express = require('express');

  fs = require('fs');

  readline = require('readline');

  router = express.Router();

  module.exports = router;

  stat_file_size = function(name) {
    var path, stats;
    path = settings.logs_dir + "/" + name;
    if (!fs.existsSync(path)) {
      return null;
    }
    stats = fs.statSync(path);
    if (!stats.isFile()) {
      return null;
    }
    if (stats.size > 1024 * 1024) {
      return Math.round(stats.size / 1024 / 1024 * 100) / 100 + 'M';
    }
    return Math.round(stats.size / 1024 * 100) / 100 + 'K';
  };

  readlines = function(name, start) {
    var reader, result;
    if (!fs.existsSync(name)) {
      return null;
    }
    result = [];
    reader = readline.createInterface({
      input: fs.createReadStream(name)
    });
    return reader.on('line', function(line) {
      return result.add(line);
    });
  };

  router.use(function(req, res, next) {
    res.locals.pos091_size = stat_file_size('luckpay_091.log');
    res.locals.servlet_size = stat_file_size('luckpay_servlet.log');
    res.locals.sched_size = stat_file_size('luckpay_sched.log');
    res.locals.tpdu_size = stat_file_size('tpdu.log');
    res.locals.jdbc_size = stat_file_size('jdbc.log');
    return next();
  });

  router.get('/', function(req, res, next) {
    return res.redirect('/logs/luckpay_091');
  });

  get_level = function(str) {
    switch (str) {
      case 'FATAL':
        return 1;
      case 'ERROR':
        return 2;
      case 'WARN':
        return 3;
      case 'INFO':
        return 4;
      case 'DEBUG':
        return 5;
      case 'TRACE':
        return 6;
      default:
        return null;
    }
  };

  router.all('/:path', function(req, res, next) {
    var filepath, last_level, level_int, line_no, lines, reader, regex;
    filepath = settings.logs_dir + "/" + req.params.path + ".log";
    if (!fs.existsSync(filepath)) {
      return next(new Error('日志文件 ' + filepath + ' 不存在.'));
    }
    res.locals.path = req.params.path;
    res.locals.keyword = req.body.keyword || '';
    res.locals.level = req.body.level;
    level_int = get_level(res.locals.level) || 99;
    res.locals.start_no = parseInt(req.body.start_no) || 0;
    res.locals.max_lines = parseInt(req.body.max_lines) || 500;
    regex = /^(.+) \[(.+) ([a-zA-Z0-9_]+)\] ([a-zA-Z]+) - (.*)$/;
    lines = [];
    reader = readline.createInterface({
      input: fs.createReadStream(filepath)
    });
    line_no = 0;
    last_level = 'INFO';
    reader.on('line', function(line) {
      var log_line, matchs;
      line_no += 1;
      if (res.locals.start_no > 0 && line_no < res.locals.start_no) {
        return;
      }
      if (res.locals.keyword.length > 0) {
        if (line.indexOf(res.locals.keyword) < 0) {
          return;
        }
      }
      log_line = {
        line_no: line_no,
        level: last_level
      };
      matchs = regex.exec(line);
      if (matchs) {
        log_line.time = matchs[1];
        log_line.thread = matchs[2];
        log_line.logger = matchs[3];
        log_line.level = matchs[4];
        log_line.message = matchs[5];
        last_level = log_line.level;
      } else {
        log_line.message = line;
      }
      if ((get_level(log_line.level) || 1) <= level_int) {
        lines.push(log_line);
      }
      if (lines.length >= res.locals.max_lines) {
        if (res.locals.start_no > 0) {
          return reader.close();
        }
        return lines.shift();
      }
    });
    return reader.on('close', function() {
      return res.render('logs', {
        lines: lines
      });
    });
  });

}).call(this);
